package com.bear.newsset.ui.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bear.newsset.R;
import com.bear.newsset.adapter.NewsListAdapter;
import com.bear.newsset.dao.entity.NewsLikeSqlEntity;
import com.bear.newsset.dao.sql.NewsDataSQL;
import com.bear.newsset.dao.sql.NewsStatusSQL;
import com.bear.newsset.entity.NewsListEntity;
import com.bear.newsset.util.ActionUtil;
import com.bear.newsset.util.DOM;
import com.bear.newsset.util.LogUtils;
import com.bear.newsset.util.Utils;
import com.bear.newsset.widget.BaseActivity;
import com.bear.newsset.widget.item.BaseNewsItemView;
import com.bumptech.glide.Glide;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.ybear.ybmvp.annotations.BindView;

import java.util.List;

import static com.bear.newsset.util.Constant.DOM_ID_NEWS_MANAGE_ACTIVITY_DESTROY;

/**
 * 新闻管理页面
 */
public class NewsManageActivity extends BaseActivity {
    public static final String TITLE_NAME = "NEWS_MANAGE_TITLE_NAME";
    public static final String TYPE_NAME = "NEWS_MANAGE_TYPE_NAME";
    public static final int TYPE_HISTORY = 1000;
    public static final int TYPE_GIVE_LIKE = 1001;
    public static final int TYPE_COLLECTION = 1002;
    public static final int TYPE_SHARE = 1003;

    @BindView(R.id.news_manage_inc_manage)
    private View vManage;

    @BindView(R.id.tb_content_iv_back_btn)
    private ImageView ivToolbarBackBtn;

    @BindView(R.id.tb_content_tv_title)
    private TextView tvToolbarTitle;

    @BindView(R.id.tb_content_tv_other_btn)
    private TextView tvToolbarOtherBtn;

    @BindView(R.id.news_manage_rv_list)
    private XRecyclerView rvView;

    private TextView tvDeleteBtn;
    private CheckBox cbSelectAll;

    private List<NewsListEntity> mData;
    private NewsListAdapter mAdpter;

    private NewsStatusSQL.NEWS_LIKE_TYPE newsType;
    private int manageType;
    private String title;
    private String account;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_manage);

        initIntent();
        initView();
        initData();
        initListener();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DOM.getInstance().setResult( DOM_ID_NEWS_MANAGE_ACTIVITY_DESTROY );
    }

    private void initIntent() {
        title = getIntent().getStringExtra(TITLE_NAME);
        manageType = getIntent().getIntExtra(TYPE_NAME, -1);
    }

    private void initView() {
        cbSelectAll = vManage.findViewById(R.id.block_news_manage_cb_select_all);
        tvDeleteBtn = vManage.findViewById(R.id.block_news_manage_tv_finish_btn);

        tvToolbarOtherBtn.setVisibility( View.VISIBLE );
        ivToolbarBackBtn.setVisibility( View.VISIBLE );
    }

    private void initData() {
        NewsStatusSQL.NEWS_LIKE_TYPE type = NewsStatusSQL.NEWS_LIKE_TYPE.ALL;

        tvToolbarTitle.setText( ( "我的" + (title == null ? "全部" : title) ) );
        tvToolbarOtherBtn.setText("管理");
        rvView.setLayoutManager(new LinearLayoutManager(this));
        rvView.setLoadingMoreEnabled( false );
        rvView.setPullRefreshEnabled( false );

        //当前账号
        account = ((NSApplication) getApplication()).getAccountEntity().getAccount();

        //查询的类型
        switch ( manageType ) {
            case TYPE_HISTORY:      //历史
                newsType = NewsStatusSQL.NEWS_LIKE_TYPE.HISTORY;
                type = NewsStatusSQL.NEWS_LIKE_TYPE.HISTORY;
                break;
            case TYPE_GIVE_LIKE:    //点赞
                newsType = NewsStatusSQL.NEWS_LIKE_TYPE.GIVE_LIKE;
                type = NewsStatusSQL.NEWS_LIKE_TYPE.GIVE_LIKE;
                break;
            case TYPE_COLLECTION:   //收藏
                newsType = NewsStatusSQL.NEWS_LIKE_TYPE.COLLECT;
                type = NewsStatusSQL.NEWS_LIKE_TYPE.COLLECT;
                break;
            case TYPE_SHARE:        //分享
                newsType = NewsStatusSQL.NEWS_LIKE_TYPE.SHARE;
                type = NewsStatusSQL.NEWS_LIKE_TYPE.SHARE;
                break;
        }
        LogUtils.d("NewsManage", "Type:" + type);
        //查询到的数据
        mData = NewsDataSQL.getInstance().queryNewsDataSqlAllForAccount( account, type);
        //设置适配器
        mAdpter = new NewsListAdapter(Glide.with( this ), mData);

        rvView.setAdapter( mAdpter );

        //设置NewsItemView的属性
        mAdpter.onSetNewsItemView(view -> {
            //隐藏喜欢和收藏按钮
            view.hideMoreBtn(
                    BaseNewsItemView.CLICK_TYPE.GIVE_LIKE, BaseNewsItemView.CLICK_TYPE.COLLECT
            );
        });

        //0条数据时隐藏管理按钮
        if( mData.size() == 0 ) tvToolbarOtherBtn.setVisibility( View.GONE );
    }

    private void initListener() {
        ivToolbarBackBtn.setOnClickListener(v -> finish());

        //toolbar右边按钮点击事件监听器
        tvToolbarOtherBtn.setOnClickListener(v -> {
            //切换多选模式
            switchMultiselectMode();
        });

        //侧滑返回
        Utils.setOnSuperTouchListener(rvView, (v, event) -> {
            onSwipeBackTouchEvent( event );
            return false;
        });

        //多选模式发生改变时事件监听器
        mAdpter.setOnChangeMultiselectModeListener((adapter, enable) -> {
            //切换标题
            tvToolbarOtherBtn.setText( enable ? "取消" : "管理" );
        });

        //Item点击事件监听器
        mAdpter.setOnItemClickListener((view, itemData, position) -> {
            if( mAdpter.isEnableMultiselectMode() ) {
                //切换Item多选状态
                mAdpter.switchItemMultiselectStatus( position );
            }else {
                //打开新闻页面
                Utils.startContentActivity(view.getContext(), itemData);
            }
        });

        //更多 - 分享按钮点击事件监听器
        mAdpter.setOnClickInsideMoreBtnListener((v, type, isSelect, itemData, position) -> {
            //分享新闻
            ActionUtil.startShare(v.getContext(), itemData.getItemData().getUrl());
        });

        mAdpter.setOnLongClickMoreListener((v, itemData) -> {
            String newsId = itemData.getItemData().getId();
            NewsLikeSqlEntity e = getLikeStatus( newsId );
            //初始化按钮状态
            v.initMoreInsideBtnStatus( e.getIsGiveLike(), e.getIsCollect(), e.getIsShare());
        });

        //全选选择按钮点击事件监听器
        cbSelectAll.setOnCheckedChangeListener((buttonView, isChecked) -> {
            //全选/反选
            mAdpter.setItemMultiselectStatusAll( isChecked );
        });

        //删除按钮点击事件监听器
        tvDeleteBtn.setOnClickListener(v -> {
            List<Boolean> statusList = mAdpter.getItemMultiselectStatusAll();

            if( mData.size() == 0 ) {
                Toast.makeText(v.getContext(), "暂无条目", Toast.LENGTH_SHORT).show();
                return;
            }

            int i = 0;
            int j = -1;
            while ( mData.size() > 0 && i != mData.size() ) {
                if( ++j >= statusList.size() ) return;
                if( !statusList.get( j ) ) {
                    i++;
                    continue;
                }
                LogUtils.e("TAG", mData.size() + "   " + i + "  " + statusList.get( j ));
//                String newsId = mData.get( i ).getItemData().getId();
//                NewsStatusSQL.getInstance().deleteNewsStatusSql(account, newsId, newsType);
                mAdpter.removeItemMultiselectStatus( i );
                mData.remove( mData.get( i ) );

            }
            mAdpter.notifyDataSetChanged();
        });

        //选择切换发生改变事件监听器
        mAdpter.setOnMultiSizeChangeListener(size -> {
            //更新删除数量
            tvDeleteBtn.setText( size == 0 ? "删除" : "删除(" + size + ")" );
        });
    }

    /**
     * 获取新闻喜欢的状态
     * @param newsId    新闻id
     * @return          喜欢的状态
     */
    @NonNull
    public NewsLikeSqlEntity getLikeStatus(String newsId) {
        return NewsStatusSQL.getInstance().queryNewsLikeSqlForNewsId( newsId );
    }

    private void switchMultiselectMode() {
        mAdpter.switchMultiselectMode();
        vManage.setVisibility( mAdpter.isEnableMultiselectMode() ? View.VISIBLE : View.GONE );
    }

    @Override
    public void finish() {
        if( mAdpter.isEnableMultiselectMode() ) {
            mAdpter.switchMultiselectMode();
        }else {
            super.finish();
        }
    }
}
